﻿using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace MyServer
{
    class Program
    {
        /// <summary>
        /// 创建Web Server
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //1.指定服务器的IP和Port
            IPAddress address = IPAddress.Parse("127.0.0.1");
            int port = 8080;

            //2.Server监听该地址
            TcpListener server = new TcpListener(address, port);
            server.Start();

            while (true)
            {
                try
                {
                    TcpClient visitor = server.AcceptTcpClient();
                    //Console.WriteLine("Accepted:"+visitor.Client.RemoteEndPoint.ToString());

                    //获取客户端发送的消息（http请求消息）
                    byte[] bytes = new byte[visitor.ReceiveBufferSize];
                    NetworkStream stream = visitor.GetStream();
                    stream.Read(bytes, 0, bytes.Length);
                    String msg = System.Text.Encoding.UTF8.GetString(bytes);
                    Console.WriteLine(msg);

                    String[] strs = msg.Split("\r\n");
                    String first = strs[0];
                    String path = first.Split(" ")[1];

                    //根据访问的地址不同，向浏览器发送不同的消息相应
                    //如“/news”，返回“Hello News”；“/about”，返回网站介绍信息等。
                    visitor.Client.Send(System.Text.Encoding.UTF8.GetBytes("HTTP/1.1 201 OK\r\n\r\n"));

                    if (path == "/news")
                    {
                        String txt = File.ReadAllText("news.html");
                        txt = txt.Replace("{name}", "Tom");
                        txt = txt.Replace("{time}", DateTime.Now.ToString());
                        visitor.Client.Send(System.Text.Encoding.UTF8.GetBytes(txt));
                    }
                    else if (path == "/nba")
                        visitor.Client.Send(System.Text.Encoding.UTF8.GetBytes("<font color='red'>Hello NBA!</font>"));
                    else
                        visitor.Client.Send(System.Text.Encoding.UTF8.GetBytes("<font color='red'>Hello World!</font>"));

                    stream.Close();
                    visitor.Close();
                }
                catch { }
            }

        }
    }
}
